package com.axzhengxin.platform.sync.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.ds.DSFactory;
import com.axzhengxin.platform.afterloan.domain.InventoryLoanInfo;
import com.axzhengxin.platform.afterloan.mapper.FspCorInfMapper;
import com.axzhengxin.platform.afterloan.mapper.InventoryLoanInfoMapper;
import com.axzhengxin.platform.sync.ISyncDataService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * InventoryLoanSyncServiceImpl
 * 同步批量上传贷款信息
 *
 * @author jiangnan
 * @date 2021/4/7
 */
@Slf4j
@Service("inventory")
public class InventoryLoanSyncServiceImpl implements ISyncDataService {

    private static final String INVENTORY_LOAN_SQL = "SELECT t.ENT_NAME AS customer_name, t.UNISCID, t.CREDIT_AMOUNT AS approve_amount, t.LOAN_START_DAY AS loan_start, t.TERM AS loan_time, t.LOAN_AMOUNT, t.INTEREST_RATE AS loan_ratio, t.LOAN_TYPE AS GUARANTEE_TYPE, t.IS_FIRST_LOAN AS if_first_loan, t.BRANCH, substr(t.id, 0, 8) AS create_time, t.PAYMENT_DAY AS approve_start, t.PAYMENT_DUE_DAY AS approve_end FROM WARNING_UPLOAD t WHERE t.TRANSSERIAL_NO IS NULL AND SUBSTR(t.id, 0, 6) IN ('202010', '202011', '202012', '202101', '202102', '202103', '202104')";

    private static Map<Long, Long> deptAdminMapper;

    @Autowired
    private InventoryLoanInfoMapper inventoryLoanInfoMapper;

    @Autowired
    private FspCorInfMapper fspCorInfMapper;

    @SneakyThrows
    @Override
    public void exec() {
        preExec();
        String profile = SpringUtils.getActiveProfile();
        Db.use(DSFactory.get(profile))
                .query(INVENTORY_LOAN_SQL)
                .stream()
                .peek(entity -> log.info("读取完成"))
                .peek(entity -> Optional.ofNullable(entity.getStr("CUSTOMER_NAME"))
                        .filter(StrUtil::isNotBlank)
                        .map(fspCorInfMapper::selectCustomerIdByCustomerName)
                        .filter(StrUtil::isNotBlank)
                        .map(fspCorInfMapper::selectFspCorInfById)
                        .ifPresent(fspCorInf -> {
                            entity.set("area_code", fspCorInf.getBranchNo());
                            entity.set("customer_id", fspCorInf.getId());
                        }))
                .peek(entity -> Optional.ofNullable(entity.getLong("BRANCH"))
                        .filter(deptAdminMapper::containsKey)
                        .map(deptAdminMapper::get)
                        .ifPresent(userId -> entity.set("CREATE_BY", userId)))
                .peek(entity -> Optional.ofNullable(entity.getStr("CREATE_TIME"))
                        .filter(StrUtil::isNotBlank)
                        .filter(createDateStr -> 8 == createDateStr.length())
                        .ifPresent(createDateStr -> {
                            try {
                                entity.set("CREATE_TIME", DateUtils.parseDate(createDateStr, "yyyyMMdd"));
                            } catch (Exception ex) {
                                log.error("解析日期失败", ex);
                            }
                        }))
                .map(entity -> entity.toBean(InventoryLoanInfo.class))
                .forEach(inventory -> inventoryLoanInfoMapper.insertInventoryLoanInfo(inventory));
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @SneakyThrows
    private void preExec() {
        String profile = SpringUtils.getActiveProfile();
        deptAdminMapper = Db.use(DSFactory.get(profile))
                .query("select u.user_id, u.dept_id from sys_user u, sys_role r, sys_user_role ur where u.user_id = ur.user_id and r.role_id = ur.role_id and r.role_key in ('banknrmadmin','ecsc_sub_1_admin','ecsc_sub_2_admin','bankvipadmin') order by u.user_id asc")
                .stream()
                .filter(MapUtil::isNotEmpty)
                .map(entity -> entity.toBeanIgnoreCase(SysUser.class))
                .collect(Collectors.toMap(SysUser::getDeptId, SysUser::getUserId,
                        BinaryOperator.minBy(Comparator.comparingLong(deptId -> deptId))));
    }

}
